/**
 * 显示固定位数的数字。
 * @param {Number} bits
 * @returns {String} 固定位数的数字(不足的在左侧补零)。
 */
Number.prototype.leftPad = function (bits, padChar) {
    padChar = padChar || '0';

    var bitsArray = [padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar, padChar];
    var length = this.toFixed(0).toString().length;

    return (length >= bits) ? this : bitsArray.slice(0, bits - length).join('') + this;
};

Date.prototype.format = function (str) {
    str = str || 'yyyy-MM-dd';
    var date = this;
    var result = '';
    var yearReg = /(y+)/g;
    var monthReg = /(M+)/g;
    var dayReg = /(d+)/g;
    var hourReg = /(H+)/g;
    var minuteReg = /(m+)/g;
    var secondReg = /(s+)/g;
    var padLength = 1;

    if (yearReg.test(str)) {
        padLength = str.match(yearReg)[0].length;
        str = str.replace(yearReg, (date.getFullYear()).leftPad(padLength));
    }

    if (monthReg.test(str)) {
        padLength = str.match(monthReg)[0].length;
        str = str.replace(monthReg, (date.getMonth() + 1).leftPad(padLength));
    }

    if (dayReg.test(str)) {
        padLength = str.match(dayReg)[0].length;
        str = str.replace(dayReg, (date.getDate()).leftPad(padLength));
    }

    if (hourReg.test(str)) {
        padLength = str.match(hourReg)[0].length;
        str = str.replace(hourReg, (date.getHours()).leftPad(padLength));
    }

    if (minuteReg.test(str)) {
        padLength = str.match(minuteReg)[0].length;
        str = str.replace(minuteReg, (date.getMinutes()).leftPad(padLength));
    }

    if (secondReg.test(str)) {
        padLength = str.match(secondReg)[0].length;
        str = str.replace(secondReg, (date.getSeconds()).leftPad(padLength));
    }

    return str;
};

String.prototype.dateFormat = function (str) {
    str = str || 'yyyy-MM-dd';
    var date = this.replace(/[年-]/, '/').replace(/[月-]/, '/').replace(/[日-]/, '/').replace(/(\/\s*)$/g, '');
    var items = date.split('/');
    var formats = str.split('-');

    if (items.length == 2) {
        return (parseInt(items[0]).leftPad(formats[0].length)) + '-' + parseInt(items[1].replace(/\s*/g, '')).leftPad(formats[1].length);
    } else if (items.length > 2) {
        return (new Date(parseInt(items[0]), parseInt(items[1]) - 1, parseInt(items[2]))).format(str);
    } else {
        return this;
    }
};